<?php
namespace app\common\command;

use app\common\logic\Order as OrderLogic;
use think\Console;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\helper\Time;
use mes\Mes;

/**
 * 定时同步今日/指定时间范围订单
 * @author King
 *
 */
class CronSyncOrder extends Command
{

	protected $logName = 'cronSyncOrder';
	protected $mes = '';
	protected $isPrint = 1;	// 是否打印信息到终端

    /**
     * @var \Redis
     */
    protected $redis;

	protected function configure()
	{
		$this->setName('cronSyncOrder')
		->addOption('mes', 'm', Option::VALUE_OPTIONAL, '来源类型(1小辉辉，2名贵坊，3十义)', 1)
		->addOption('client_ordernum', 'c', Option::VALUE_OPTIONAL, '订单号', '')
		->addOption('start', 's', Option::VALUE_OPTIONAL, '开始时间戳', 0)
		->addOption('end', 'e', Option::VALUE_OPTIONAL, '结束时间戳', 0)
		->addOption('force', 'f', Option::VALUE_OPTIONAL, '是否强制更新订单忽略hash校验(1是，0否)', 0)
		->addOption('time', 't', Option::VALUE_OPTIONAL, '当天前的第N天(如：1昨天，2前天)', 0)
		->addOption('print', 'p', Option::VALUE_OPTIONAL, '是否打印信息到终端(1是，0否)', 1)
		->addOption('history', 'y', Option::VALUE_OPTIONAL, '是否历史订单查询(1是，0否)', 0)
		->addOption('type', 'ty', Option::VALUE_OPTIONAL, '是否当天定时轮询(1是，0否)', 0)
		->setDescription('定时同步今日/指定时间订单');
	}

	protected function execute(Input $input, Output $output)
	{
        $this->redis = getRedis();
		set_time_limit(0);
		ini_set('memory_limit', '512M');
		error_reporting(E_ALL & ~E_NOTICE);

		$mes = $input->getOption('mes');
		$syncClientOrdernum = $input->getOption('client_ordernum');
		$time = $input->getOption('time');
		$forceUpdate = $input->getOption('force');
		$this->isPrint = $input->getOption('print');
		$history = $input->getOption('history');
		$type = $input->getOption('type'); // 如果是当天定时轮询，则由程序自动判断是否请求
        switch ($mes) {
            case 'client_status_6':
                return $this->client_status_6();
                break;
            case 'client_status_newapi':
                return $this->client_status_newapi();
                break;
            case 'create_order_add_auto'://今天的智能同步 拉取订单
                return $this->create_order_add_auto('', 1);
                break;
            case 'create_order_add_auto_2'://今天的智能同步 拉取订单
                return $this->create_order_add_auto('', 2);
                break;
            case 'create_order_add_auto_yestoday'://昨天的智能同步 拉取订单
                return $this->create_order_add_auto('yestoday', 1);
                break;
            case 'queryProduceOrderIds':
                return $this->queryProduceOrderIds(1, $input->getOption('start'), $input->getOption('end'), $time);
                break;
            case 'queryProduceOrderIds_2':
                return $this->queryProduceOrderIds(2, $input->getOption('start'), $input->getOption('end'), $time);
                break;
            case 'queryProduceOrderInfoById':
                return $this->queryProduceOrderInfoById();
                break;
            case 'queryProduceOrderIdsV2':
                return $this->queryProduceOrderIdsV2(1, $input->getOption('start'), $input->getOption('end'), $time);
                break;
            case 'queryProduceOrderIdsV2_2':
                return $this->queryProduceOrderIdsV2(2, $input->getOption('start'), $input->getOption('end'), $time);
                break;
            default:
                break;
        }

        $paramStr = "mes:{$mes},client_ordernum:{$syncClientOrdernum},time:{$time},force:{$forceUpdate},print:{$this->isPrint},history:{$history},type:{$type}";

		if (!in_array($mes, [1, 2, 3])) {
			$msg = "参数mes错误";
			$this->_consoleLog($msg, 'error');
			return ;
		}

		$this->mes = $mes;

		if ($syncClientOrdernum != '') {
			$orderInfo = db('order')->where('client_ordernum', $syncClientOrdernum)->where('status', '<>', 99)->field('accept_time,create_time,is_auto_import')->find();
			if ($orderInfo) {
				$forceUpdate = 1;
				$this->isPrint = 0;
				$mes = $orderInfo['is_auto_import'];
				if ($orderInfo['create_time'] > 0) {
					$startTime = $orderInfo['create_time'] - 3;
					$endTime = $orderInfo['create_time'] + 3;
				} else {
					$startTime = strtotime(date('Y-m-d 00:00:00', $orderInfo['create_time']));
					$endTime = $startTime + 86399;
				}
			} else {
				$msg = "订单号不存在";
				$this->_consoleLog($msg, 'error');

				$output->write(json_encode(['code' => 0, 'msg' => $msg], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
				return ;
			}
		} elseif ($input->hasOption('start') && $input->hasOption('end')) {
			$startTime = $input->getOption('start');
			$endTime = $input->getOption('end');
		} elseif ($time > 0) {
			list($startTime, $endTime) = Time::today();
			$startTime = $startTime - $time*86400;
			$endTime = $endTime - $time*86400;
		} else {
			if (intval(date('H')) < 1) {
				list($startTime, $endTime) = Time::yesterday(); // 凌晨1点前都取昨天
                $startTime = $endTime-3600*3;
			} else {
				list($startTime1, $endTime) = Time::today();
                $startTime2 = $endTime-3600*3;
                $startTime = max($startTime1, $startTime2);
			}

			if ($type == 1) {
				$h = intval(date('H'));
				if ($h >= 8) {
					// 规定 时间内可以执行
				} else {
					$this->_consoleLog('定时轮询未到可执行时间点', 'start');
					return ;
				}
			}

		}

		$startTimeStr = date('Y-m-d H:i:s', $startTime);
		$endTimeStr = date('Y-m-d H:i:s', $endTime);

		$msg = "开始同步订单...[{$startTimeStr} ~ {$endTimeStr}]".$paramStr;
		$this->_consoleLog($msg, 'start');

		try {
			$mesLib = new Mes();

			$config = [
				'private_key' => env("mes{$mes}.private_key"),
				'app_id' => env("mes{$mes}.app_id"),
				'app_secure' => env("mes{$mes}.app_secure"),
				'host' => env("mes{$mes}.host"),
			];
			$mesLib->setConfig($config);
			$result = $mesLib->queryProduceOrderInfo($startTimeStr, $endTimeStr);
            addLog($result, 'queryProduceOrderInfo');
			$response = json_decode($result, true);

			if ($response['code'] == 0) {
				$list = $response['info'];
				$produceOrderIdArr = [];
				$msg = "本次发现订单 ".count($list)."个, produceOrderIds:" . implode(',', array_column($list, 'produceOrderId'));
				$this->_consoleLog($msg, 'produceOrderIds');

				$waitOrders = []; // 待接单订单且需要提醒的
				$syncOrders = []; // 本次同步处理的订单
				$totalOrders = array_column($list, 'produceOrderId'); // 本次发现的订单
				foreach ($list as $k => $v) {
                    $this->_flag_daiDingDang('update', $v, $mes,$forceUpdate);
					$clientOrdernum = $v['produceOrderId']; // 客户订单号
					$clientOrderStatus = $v['status']; // 客户订单号接单状态

					// 同步指定订单号
					if ($syncClientOrdernum != '' && $syncClientOrdernum != $clientOrdernum) {
						continue;
					}

					// 待接单提醒
					if ($clientOrderStatus == '待接单') {
						if (!cache('?' . ORDER_WAIT . $clientOrdernum)) {
							$waitOrders[] = $clientOrdernum;
							cache(ORDER_WAIT . $clientOrdernum, date('Y-m-d H:i:s'), 10*86400);
						}
						continue;
					}

					// 检测订单号有无更新
					$orderMd5 = md5(json_encode($v));
					$key = ORDER_HASH . $clientOrdernum;
					if (!cache('?'. $key) || cache($key) != $orderMd5 || $forceUpdate) {
						cache($key, $orderMd5, 60*86400);
						$v['mes'] = $mes;
						$v['history'] = $history;
						queue('app\common\job\SyncOrder', json_encode($v), rand(0, 10), 'SyncOrder');
						$syncOrders[] = $clientOrdernum;
						$this->_consoleLog("订单{$clientOrdernum}已进入消费队列", 'add2Queue');
					}
				}

				if ($waitOrders) {
					if (config('mp.wework_user_alarm_wait_order') != '') {
						$users = array_filter(explode(',', config('mp.wework_user_alarm_wait_order')));
						if ($users) {
							try {
								$wework = new \Wework();
								$res = $wework->textMessageSend("MES有".count($waitOrders)."个待接单订单需要您处理，订单号：".implode(',', $waitOrders), $users);
								$this->_consoleLog("预警结果:".json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE), 'wework');
							} catch (\Exception $e) {
								$this->_consoleLog("预警失败:".$e->getMessage(), 'wework');
							}
						}
					}

					$this->_consoleLog("订单".implode(',', $waitOrders)."待接单预警", 'waitOrders');
				}
				$this->_consoleLog("订单同步完成", 'end');

				$output->write(json_encode(['code' => 1, 'msg' => '处理成功', 'data' => ['start'=>$startTime, 'end'=>$endTime, 'time' => $time, 'force' => $forceUpdate, 'print' => $this->isPrint, 'totalOrders' => $totalOrders, 'syncOrders' => $syncOrders, 'waitOrders' => $waitOrders]], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
			} else {
				throw new \Exception($response['msg']);
			}

		} catch (\Exception $e) {
			$msg = "错误:".$e->getMessage().'，line:'.$e->getLine();
			$this->_consoleLog($msg, 'Exception');
			$output->write(json_encode(['code' => 0, 'msg' => $msg, 'data' => ['start'=>$startTime, 'end'=>$endTime, 'time' => $time, 'force' => $forceUpdate, 'print' => $this->isPrint, 'totalOrders' => $totalOrders, 'syncOrders' => $syncOrders, 'waitOrders' => $waitOrders]], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
		}
	}

	/**
	 * 记录日志并打印
	 *
	 * @author KING
	 * @date 2020年6月11日
	 *
	 * @param string $msg
	 * @param string $flag
	 * @param string $format
	 */
	private function _consoleLog($msg, $flag, $format=true) {
		if ($this->isPrint) consoleLog($msg, $flag, $format);
		addLog($msg, $this->logName . $this->mes);
	}

    /**
     * 同步订单状态--一般有1696个订单没完成的要同步
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/27
     */
    private function client_status_6()
    {
        $order_logic = (new \app\common\logic\Order());
        //1,如redis订单为空里，查询要同步的订单，放入redis里
        $redis = getRedis();
        $order_id = $redis->lPop('client_status_6');
        if ($order_id == false) {
            $list = db('order o')
                ->field(" o.id")
                ->where([
//                    ['o.client_ordernum', '=', '8306148'],
                    ['o.status', 'in', [0, 1]],
                ])->select();
            foreach ($list as $k => $v) {
                $redis->lpush('client_status_6', $v['id']);
            }
            $order_id = $redis->lPop('client_status_6');
        }
        //2,从redis取出要同步的订单号，进行同步，同步完就立即清除redis的订单号
        $order_id_array = [];
        $order_id_array[] = $order_id;
        for ($i = 0; $i < 10; $i++) {
            $temp = $redis->lPop('client_status_6');
            if ($temp == false) {
                break;
            }
            $order_id_array[] = $temp;
        }
        foreach ($order_id_array as $k => $v) {
            $res = $order_logic->sync_one($v);
            sleep(rand(5, 10));
        }
        echo "Done" . PHP_EOL;
        return false;
    }

    /**
     *  同步客户订单状态 --新版本接口
     * @author  huanghuixiang
     * @date 2022/10/21 16:11
     */
    public function client_status_newapi(){
         //指定每天同步时间
        $sync_time= ["07:55","09:59","13:25","15:30","17:30","19:30"];
        $hours_min=date("H:i");
        if(in_array($hours_min,$sync_time)){
            $order_logic = (new \app\common\logic\Order());
            $order_logic-> _syncOrderStatus();
            echo "Done" . PHP_EOL;
        }
    }

    /**
     * 智能同步 拉取订单
     * wx_sync_order_config 记录今天同步的状态。只记录当天
     * php think cronSyncOrder -m create_order_add_auto
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/24
     */
    private function create_order_add_auto($type = '', $mes = 1)
    {
        switch ($type) {
            case 'yestoday'://昨天如还有待接单 智能拉取
                switch ($mes) {
                    case 1:
                        //1,查询是否到时间 与原时间 差3分钟 避免mes系统反应不过来
                        $time_array = [];
                        $this->_create_order_add_auto_find($time_array, $mes, 'yestoday');
                        //2,根据参数同步订单
                        foreach ($time_array as $k => $v) {
                            $output = Console::call('cronSyncOrder', ['--print=1', '--start=' . $v['startTime'], '--end=' . $v['endTime'], '--mes=' . $mes, '--force=1']);
                        }
                        echo "Done" . PHP_EOL;
                        return false;
                        break;
                    case 2:
                        break;
                }
                break;
            default://今天的同步
                switch ($mes) {
                    case 1:
                        $time_array = [];
                        $this->_create_order_add_auto_find($time_array, $mes);
                        //2,根据参数同步订单
                        foreach ($time_array as $k => $v) {
                            $output = Console::call('cronSyncOrder', ['--print=1', '--start=' . $v['startTime'], '--end=' . $v['endTime'], '--mes=' . $mes, '--force=1']);
//                sleep(60);
//            $resA = json_decode($output->fetch(), true);
                        }
                        echo "Done" . PHP_EOL;
                        return false;
                        break;
                    case 2:
                        $time_array = [];
                        //1.2，3小时前的订单拉一下。
                        $this->_create_order_add_auto_find($time_array, $mes);
                        //2,根据参数同步订单
                        foreach ($time_array as $k => $v) {
                            $output = Console::call('cronSyncOrder', ['--print=1', '--start=' . $v['startTime'], '--end=' . $v['endTime'], '--mes=' . $mes, '--force=1']);
//                sleep(60);
//            $resA = json_decode($output->fetch(), true);

                        }
                        echo "Done" . PHP_EOL;
                        return false;
                        break;
                }
                break;
        }
    }

    private function _create_order_add_auto_find(&$time_array, $mes, $type = '')
    {
        //1,查询是否到时间
        $now_h_m = date('H:i', time());
//        $now_h_m='15:00';
        $sql = "SELECT sc.* 
FROM wx_sync_order_config sc
WHERE type='{$type}' and mes={$mes} and start_time<>'0000-00-00 00:00:00'
and date_format(sc.fire_time,'%H:%i') ='{$now_h_m}' ";
        $list = db('sync_order_config')->query($sql);
        if ($list == []) {
            return false;
        }
        foreach ($list as $k => $v) {
            $start_h_i = date('H:i', strtotime($v['start_time']));
            $end_h_i = date('H:i', strtotime($v['end_time']));
            $startTime = strtotime(date("Y-m-d {$start_h_i}:00", time()));
            $endTime = strtotime(date("Y-m-d {$end_h_i}:59", time()));
            if ($type == 'yestoday') {
                //昨天处理
                $startTime = mktime(intval(date('H', $startTime)), intval(date('i', $startTime)), intval(date('s', $startTime)), intval(date('m', $startTime)), date('d', $startTime) - 1, date('Y', $startTime));
                $endTime = mktime(intval(date('H', $endTime)), intval(date('i', $endTime)), intval(date('s', $endTime)), intval(date('m', $endTime)), date('d', $endTime) - 1, date('Y', $endTime));
            }
            $time_array[] = [
                'startTime' => $startTime - ($start_h_i == '00:00' ? 0 : 10),//退后10秒，确保mes系统数据完整  错误:时间必须为同一天
                'endTime' => $endTime,
            ];
        }
        return true;
    }

    /**
     * 订单同步
     * 1，queryProduceOrderIds接口，查订单号，并与本地对比，得出要添加的订单
     * 2，queryProduceOrderInfoById接口，查询订单全面信息而添加订单
     * @param int $mes
     * @param int $startTime
     * @param int $endTime
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/31
     */
    private function queryProduceOrderIds($mes = 1, $startTime = 0, $endTime = 0, $time = 0)
    {
        if ($time > 0) {
            list($startTime, $endTime) = Time::today();
            $startTime = $startTime - $time * 86400;
            $endTime = $endTime - $time * 86400;
        }
        $startTimeStr = date('Y-m-d H:i:s', strtotime(date('Y-m-d 00:00:00')));
        $endTimeStr = date('Y-m-d H:i:s', time());
        $startTime > 0 && $startTimeStr = date('Y-m-d H:i:s', $startTime);
        $endTime > 0 && $endTimeStr = date('Y-m-d H:i:s', $endTime);
        $msg = "开始同步订单...[{$startTimeStr} ~ {$endTimeStr}]";
        $this->_consoleLog($msg, 'start');
        $mesLib = new Mes();
        $config = [
            'private_key' => env("mes{$mes}.private_key"),
            'app_id' => env("mes{$mes}.app_id"),
            'app_secure' => env("mes{$mes}.app_secure"),
            'host' => env("mes{$mes}.host"),
        ];
        $mesLib->setConfig($config);
        $result = $mesLib->queryProduceOrderIds($startTimeStr, $endTimeStr);
        addLog($result, 'queryProduceOrderIds');
        $response = json_decode($result, true);
        if (isset($response['info']) && count($response['info']) > 0) {
            $nowOrderList = db('order o')->field('o.id,o.client_ordernum')
                ->where([
                ['o.client_ordernum', 'in', $response['info']],
            ])->select();
            $new_produceOrderId = [];
            foreach ($response['info'] as $k => $produceOrderId) {
                $flag = 0;
                foreach ($nowOrderList as $k2 => $v) {
                    if ($v['client_ordernum'] == $produceOrderId) {
                        $flag = 1;
                    }
                }
                $temp_res=$this->_flag_daiDingDang('select',$produceOrderId);
                $startTime == 0 && $temp_res == 1 && $flag = 1;
                $flag == 0 && $new_produceOrderId[] = $produceOrderId;
            }
            if ($new_produceOrderId != []) {
                $pi_flag=0;
                foreach ($new_produceOrderId as $k => $produceOrderId) {
                    if($pi_flag==1){ //主要是因为只要一个订单在待接单，基本上其它后面的订单都是待接单的状态
                        $this->_flag_daiDingDang('set_order_id',$produceOrderId);
                        continue;
                    }
                    $mesInfo_json = $mesLib->queryProduceOrderInfoById($produceOrderId);
                    addLog($mesInfo_json, 'queryProduceOrderInfoById');
                    $mesInfo = json_decode($mesInfo_json, true);
                    if($mesInfo['code']<0){
                        $this->_consoleLog("订单{$produceOrderId}--{$mesInfo['msg']}", 'syncOrder_finish');
                        continue;
                    }
                    $mesInfo['info']['mes']=$mes;
                    $temp=$this->_flag_daiDingDang('set',$mesInfo['info']);
                    if($temp==true){
                        $pi_flag=1;
                    }
                    (new OrderLogic())->sync($mesInfo['info'], true);
                    $this->_consoleLog("订单{$mesInfo['info']['produceOrderId']}同步完成", 'syncOrder_finish');
                }
            }
        }
    }

    /**
     * 待接单的订单迟点查询 50分钟后，免得太多次访问
     * @param string $type
     * @param $mesInfo
     * @return bool|mixed|string
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/31
     */
    private function _flag_daiDingDang($type = 'select', $mesInfo, $mes = 1, $forceUpdate = 0)
    {
        switch ($type) {
            case 'select':
                $temp = $this->redis->get("daijidan_{$mesInfo}");
                return $temp;
                break;
            case 'set':
                $temp = $this->redis->get("daijidan_ok_{$mesInfo}");
                if ($temp == 1) {
                    return false;
                }
                if ($mesInfo['status'] == '待接单') {
                    $this->_consoleLog("订单{$mesInfo['produceOrderId']}--待接单", 'syncOrder_finish');
                    return $this->redis->setex("daijidan_{$mesInfo['produceOrderId']}", 25 * 60, 1);//40分钟
                }
                return false;
                break;
            case 'set_order_id':
                $temp = $this->redis->get("daijidan_ok_{$mesInfo}");
                if ($temp == 1) {
                    return false;
                }
                return $this->redis->setex("daijidan_{$mesInfo}", 25 * 60, 1);//40分钟
                break;
            case 'update':
                //1,入队处理
                if ($mesInfo['status'] != '待接单') {
                    $temp = $this->redis->rawCommand('SADD', 'can_get_queryProduceOrderInfoById_' . date('Ymd'), "{$mesInfo['produceOrderId']},$mes,{$forceUpdate}");
                    return true;
                }
                //100，旧处理方式
                $temp = $this->redis->get("daijidan_{$mesInfo['produceOrderId']}");
                if ($temp == 1 && $mesInfo['status'] != '待接单') {
                    $this->_consoleLog("订单{$mesInfo['produceOrderId']}--待接单解除", 'syncOrder_finish');
                    $this->redis->setex("daijidan_ok_{$mesInfo}", 120 * 60, 1);
                    return $this->redis->del("daijidan_{$mesInfo['produceOrderId']}");
                }
                return false;
                break;
        }
    }

    /**
     * 查询不是待接单的订单，而结合情况，拉取订单
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/2
     */
    public function queryProduceOrderInfoById()
    {
        $this->redis->rawCommand('DEL', 'can_get_queryProduceOrderInfoById_' . date('Ymd', mktime(0, 0, 0, date('m'), date('d') - 3, date('Y'))));
        $can_list = $this->redis->rawCommand('SMEMBERS', 'can_get_queryProduceOrderInfoById_' . date('Ymd'));
        if (count($can_list) <= 0) {
            $this->_consoleLog('没订单查询', 'no');
            return false;
        }
        $mesLib = new Mes();
        $produceOrderId_array = [];
        $produceOrderId_ary_min = [];
        foreach ($can_list as $k => $v_str) {
            $temp = explode(',', $v_str);
            $produceOrderId_array[] = [
                'produceOrderId' => $temp[0],
                'mes' => $temp[1],
                'forceUpdate' => intval($temp[2]),
            ];
            $produceOrderId_ary_min[] = $temp[0];
        }
        $nowOrderList = db('order o')->field('o.id,o.client_ordernum')
            ->where([
                ['o.client_ordernum', 'in', $produceOrderId_ary_min],
            ])->select();
        $new_produceOrderId = [];
        foreach ($produceOrderId_array as $k => $v) {
//            if ($v['forceUpdate'] == 1) {
//                $new_produceOrderId[] = $v;
//                continue;
//            }
            $flag = 0;
            foreach ($nowOrderList as $k2 => $v2) {
                if ($v2['client_ordernum'] == $v['produceOrderId']) {
                    //删除已存在的订单，不用拉新单
                    $temp = implode(',', [$v['produceOrderId'], $v['mes'], $v['forceUpdate']]);
                    $this->redis->rawCommand('SREM', 'can_get_queryProduceOrderInfoById_' . date('Ymd'), $temp);
                    $flag = 1;
                    break;
                }
            }
            $flag == 0 && $new_produceOrderId[] = $v;
        }
        if ($new_produceOrderId == []) {
            $this->_consoleLog('没订单查询', 'no2');
            return false;
        }

        foreach ($new_produceOrderId as $k => $v) {
            $produceOrderId = $v['produceOrderId'];
            $mes = intval($v['mes']);
            $config = [
                'private_key' => env("mes{$mes}.private_key"),
                'app_id' => env("mes{$mes}.app_id"),
                'app_secure' => env("mes{$mes}.app_secure"),
                'host' => env("mes{$mes}.host"),
            ];
            $mesLib->setConfig($config);
            $mesInfo_json = $mesLib->queryProduceOrderInfoById($produceOrderId);
            addLog($mesInfo_json, 'queryProduceOrderInfoById');
            $mesInfo = json_decode($mesInfo_json, true);
            if ($mesInfo['code'] < 0) {
                $this->_consoleLog("订单{$produceOrderId}--{$mesInfo['msg']}", 'error');
                continue;
            }
            $mesInfo['info']['mes'] = $mes;
            (new OrderLogic())->sync($mesInfo['info'], true);
            $this->_consoleLog("订单{$mesInfo['info']['produceOrderId']}同步完成", 'finish');
        }
    }


    /**
     * 订单同步
     * 1，queryProduceOrderIds接口，查订单号，并与本地对比，得出要添加的订单
     * 2，queryProduceOrderInfoById接口，查询订单全面信息而添加订单
     * @param int $mes
     * @param int $startTime
     * @param int $endTime
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/31
     */
    private function queryProduceOrderIdsV2($mes = 1, $startTime = 0, $endTime = 0, $time = 0)
    {
        if ($time > 0) {
            list($startTime, $endTime) = Time::today();
            $startTime = $startTime - $time * 86400;
            $endTime = $endTime - $time * 86400;
        }
        $startTimeStr = date('Y-m-d H:i:s', strtotime(date('Y-m-d 00:00:00')));
        $endTimeStr = date('Y-m-d H:i:s', time());
        $startTime > 0 && $startTimeStr = date('Y-m-d H:i:s', $startTime);
        $endTime > 0 && $endTimeStr = date('Y-m-d H:i:s', $endTime);
        $msg = "开始同步订单...[{$startTimeStr} ~ {$endTimeStr}]";
        $this->_consoleLog($msg, 'start');
        $mesLib = new Mes();
        $config = [
            'private_key' => env("mes{$mes}.private_key"),
            'app_id' => env("mes{$mes}.app_id"),
            'app_secure' => env("mes{$mes}.app_secure"),
            'host' => env("mes{$mes}.host"),
        ];
        $mesLib->setConfig($config);
        $result = $mesLib->queryProduceOrderIds($startTimeStr, $endTimeStr);
        addLog($result, 'queryProduceOrderIds');
        $response = json_decode($result, true);
        if (isset($response['info']) && count($response['info']) > 0) {
            $nowOrderList = db('order o')->field('o.id,o.client_ordernum')
                ->where([
                    ['o.client_ordernum', 'in', $response['info']],
                ])->select();
            $new_produceOrderId = [];
            foreach ($response['info'] as $k => $produceOrderId) {
                $flag = 0;
                foreach ($nowOrderList as $k2 => $v) {
                    if ($v['client_ordernum'] == $produceOrderId) {
                        $flag = 1;
                    }
                }
                $flag == 0 && $new_produceOrderId[] = $produceOrderId;
            }
            if ($new_produceOrderId != []) {
                foreach ($new_produceOrderId as $k => $produceOrderId) {
                    $mesInfo_json = $mesLib->queryProduceOrderInfoById($produceOrderId);
                    addLog($mesInfo_json, 'queryProduceOrderInfoById');
                    $mesInfo = json_decode($mesInfo_json, true);
                    if($mesInfo['code']<0){
                        $this->_consoleLog("订单{$produceOrderId}--{$mesInfo['msg']}", 'syncOrder_finish');
                        continue;
                    }
                    $mesInfo['info']['mes']=$mes;
                    $temp=$this->_flag_daiDingDang('set',$mesInfo['info']);
                    (new OrderLogic())->sync($mesInfo['info'], true);
                    $this->_consoleLog("订单{$mesInfo['info']['produceOrderId']}同步完成", 'syncOrder_finish');
                }
            }
        }
    }

}